onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js")).then(() => loadScript("../js/crud.js")).then(() => {
        let jobTypeOperator = new Crud({
            module: "jobType",
            hasCheckbox: true,
            iterators: [],
            rowBtn: ["edit", "delete", {
                "caption": "icon-icon-sort-name-up", "class": "btn-warning", "callback": e => {
                    e.stopPropagation();
                    const id = parseInt(e.target.closest("button").getAttribute("data-id"));
                    ajax(`/charge_code/list`, {method: "POST", body: {data: {}, pageSize: -1}}, function (data) {
                        const leftElement = document.getElementById("leftList");
                        leftElement.innerHTML = "";
                        document.getElementById("rightList").innerHTML = "";
                        document.getElementById("rightList").dataset.id = String(id);
                        data.data.forEach(item => {
                            const li = `<li class="list-group-item d-flex justify-content-between align-items-center" data-id="${item.chargeCodeId}">
                                <div class="ms-2 me-auto">
                                    <div class="fw-bold">${item.code}</div>
                                    ${item.description}
                                </div>
                                <button class="btn btn-sm btn-outline-primary" onclick="moveToRight(this)">→</button>
                            </li>`;
                            leftElement.innerHTML += li;
                        });
                    });
                    ajax(`/job_type/charge?jobTypeId=${id}`, {}, function (data) {
                        const leftList = document.getElementById("leftList");
                        const la = leftList.querySelectorAll("li");
                        data.data.forEach(item => {
                            item && la.forEach(li => {
                                if (li.dataset.id === String(item.chargeCodeId)) {
                                    moveToRight(li);
                                }
                            })
                        });
                        console.log("sub data", data);
                    });
                    new bootstrap.Modal(document.getElementById("dualListModal")).show();
                }
            }],
            opsButton: ["new"],
            search: [{"caption": "Name", "type": "text", "name": "name", class: "col-3"},
                {"caption": "Code", "type": "text", "name": "code", class: "col-3"}
            ],
            listField: [{"caption": "ID", "field": "jobTypeId"}, {"caption": "Name", "field": "name"},
                {"caption": "Code", "field": "code"}, {"caption": "Last Update Time", "field": "updateTime"}],
            editFields: [
                {"name": "code", "placeHolder": "client name", "required": "required"},
                {"name": "name", "placeHolder": "client code", "required": "required"}
            ]

        });
        jobTypeOperator.init();
        new Sortable(document.getElementById('rightList'), {
            animation: 150
        });
    }).catch((err) => console.error(err));
}

function moveToRight(button) {
    const li = button.closest("li");
    console.log("move");
    const newLi = li.cloneNode(true);
    newLi.querySelector("button").remove(); // remove the move button
    document.getElementById("rightList").appendChild(newLi);
    li.remove();
}

function submitSelection() {
    const rightList = document.getElementById("rightList");
    const parameters = new URLSearchParams({jobTypeId: rightList.dataset.id});
    Array.from(rightList.children).forEach(li => parameters.append("chargeCode", li.dataset.id));
    ajax(`/job_type/updateCharge?${parameters.toString()}`, {}, data => {
        if (data.code === 0) {
            const modalEl = document.getElementById('dualListModal');
            const modal = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
            modal.hide();
        } else {
            showToast(err);
        }
    },err=>{
        showToast(err);
    });
}

function showToast(message, delay = 3000) {
    const toastContainer = document.getElementById('_toastContainer');

    const toastEl = document.createElement('div');
    toastEl.className = 'toast align-items-center text-bg-primary border-0';
    toastEl.setAttribute('role', 'alert');
    toastEl.setAttribute('aria-live', 'assertive');
    toastEl.setAttribute('aria-atomic', 'true');

    toastEl.innerHTML = `
    <div class="d-flex">
      <div class="toast-body">${message}</div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
    </div>
  `;
    toastContainer.appendChild(toastEl);
    const toast = new bootstrap.Toast(toastEl, { delay });
    toast.show();
}